<?php

class LikeController
{
    private $likeModel;
    private $followModel;
    private $autoUidModel;
    private $diaryListModel;
    private $diaryAttachmentModel;
    private $feedModel;
    private $diaryListCacheModel;
    private $messageBoxModel;
    private $shopModel;
    private $topicModel;
    private $messageService;

    function __construct()/*{{{*/
    {
        $this->likeModel            =   new LikeModel();
        $this->followModel          =   new FollowModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->diaryListModel       =   new DiaryListModel();
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->feedModel            =   new FeedModel();
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
        $this->messageBoxModel      =   new MessageBoxModel();
        $this->shopModel            =   new ShopModel();
        $this->topicModel           =   new TopicModel();
        $this->messageService       =   new MessageService();
        $this->actions          =   array(
                'applyCreateCondition',
                'createChatGroup','getChatGroupInfo','editChatGroupInfo',
                'allChatGroups','searchChatGroups',
                'inviteFansToChatGroup','setChatGroupAdmins',
                'joinChatGroup','quitChatGroup','disbandGroup',
                'getChatUserInfo','getChatUsers','getMyJoinedGroups',
                'setGroupUserRemark','handleRequest','getPendingRequests',
                'postGroupChat','getGroupChatList','applyForGroupCertification',
                'upgradeMyChatGroup','applyCreateConditionNew'
        );
    }/*}}}*/
    
    public function callApi($param)/*{{{*/
    {
        $ac = $param['action'];
        # check $do /*{{{*/
        $doCheck    =   $this->checkAction($ac);
        if (!empty(AC::$errorNo))
        {
            return  $doCheck;
        } /*}}}*/
    
        return $this->$ac($param);
    }/*}}}*/
    
    public function applyCreateCondition($param){
        $uid  = intval($param['uid']);
        if ($uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 非本人
        if($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }

        $conditionInfo = $this->checkConditions($uid);
        $total_num = intval($conditionInfo['joined_num'] + $conditionInfo['created_num']);
        $list  = array();
        $list['condition'][] = $this->checkLevelCondition($conditionInfo);
        $list['condition'][] = $this->checkAbilityCondition($conditionInfo);
        $list['condition'][] = $this->checkJoinedCondition($conditionInfo);
        $list['condition'][] = $this->checkCreateCondition($conditionInfo);
        AC::$openApplyGroupVipVersion && $list['condition'][] = $this->checkVipCondition($conditionInfo);
        $list['infos']  =   (Object) array();

        $level_result = $ability_result = $Joined_result = $created_result = 0;
        $level_result   = $list['condition'][0]['result'];
        $ability_result = $list['condition'][1]['result'];
        $Joined_result  = $list['condition'][2]['result'];
        $created_result = $list['condition'][3]['result'];
        if (($level_result == 1 || $ability_result == 1) &&  $Joined_result == 1 &&  $created_result == 1){
            if ($level_result == 0){
                unset($list['condition'][0]);
            }
            if ($ability_result == 0){
                unset($list['condition'][1]);
            }
        }else{
            if ($level_result == 1 || $ability_result == 1){
                unset($list['condition'][0]);
                unset($list['condition'][1]);
            }
            if ($Joined_result == 1 ){
                unset($list['condition'][2]);
            }
            if ($created_result == 1 ){
                unset($list['condition'][3]);
            }
        }

        $result = array();
        $result['infos'] = $list['infos'];
        foreach ($list['condition'] as $value){
            $result['condition'][] = $value;
        }
        return $result;
    }

    public function applyCreateConditionNew($param){
        $uid  = intval($param['uid']);
        if ($uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }

        // 非本人
        if($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        //获取用户群组相关信息
        $conditionInfo = $this->checkConditions($uid);

        //会员用户验证
        if($conditionInfo['type'] == 2 && AC::$openApplyGroupVipVersion) {
            $result = $this->checkVipConditionNew($conditionInfo);
        }else{
            //非会员用户验证
            $result = $this->checkUserCondition($conditionInfo);
        }
        if(!isset($result['vip_content'])) {
            $result['vip_content'] = '会员用户无限制条件，可直接创建群组，并且可以额外再创建3个群';
        }
        if(!isset($result['ability_content'])) {
            $result['ability_content'] = '达人或等级满15级的用户，只需满足其中任一条件即有资格创建1个群';
        }

        return $result;
    }
    
    /**
     * 申请群组认证
     * @param unknown $param
     */
    private function applyForGroupCertification($param){
        $uid = $param['uid'];
        $gid = $param['gid'];
        
        // 非本人
        if($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 非创建者不能操作
        if ($group['uid'] != $uid){
            AC::$errorNo = 'LGC006';
            return  FALSE;
        }
        
        $result = array();
        $result['condition'][]  = $this->checkCertificationMemberNumCondition($group['member_num']);
        $result['condition'][]  = $this->checkCertificationLevelCondition($group['level']);
        $result['condition'][]  = $this->checkCertificationAbilityNumsCondition($gid);
        $result['condition'][]  = $this->checkCertificationCreaterIsAbilityCondition($uid);
        $result['infos']  =   (Object) array();
        
        return $result;
    }
    
    private function checkConditions($uid){
        $info = AC::$hostUserBaseInfo;
        $max_group_num     = AC::USER_GROUP_MAX_NUM;
        // 创群最大群数-人数,vip-10-100,普通-5-50
        $type              = 1;
        $max_group_num     = AC::USER_GROUP_MAX_NUM;
        $max_group_members = ExpLevel::$grouplevelAddLimit[1];
        $vipInfo = $this->autoUidModel->getUserVipInfo($uid);
        if ($vipInfo){
            $type           = 2;
            $max_group_num     = AC::VIP_GROUP_MAX_NUM;
            $max_group_members = AC::VIP_GROUP_MAX_MEMBERS;
        }
        
        // 已加入或创建群的情况
        $groups = $this->likeModel->getGroupsByUid($uid, 0);
        
        $num = $joinedNum = 0;
        if ($groups){
            foreach ($groups as $value){
                $groupInfo = $this->likeModel->getChatGroupInfoByGid($value['gid']);
                if ($groupInfo && $value['role'] == 1){
                    $num++;
                }elseif($groupInfo && $value['role'] != 1){
                    $joinedNum++;
                }
            }
        }
        
        $data = array(
                'level'         =>    intval($info['level']),
                'is_ability'    =>    intval($info['is_ability']),
                'joined_num'    =>    $joinedNum,
                'created_num'   =>    $num,
                'max_group_num' =>    $max_group_num,
                'max_group_members'    =>    $max_group_members,
                'type'                 =>    $type
        );
        return $data;
    }

    private function checkCreateCondition($info){
        $data = array();
        $create_num = $info['created_num'];
        $data['name']  = 'group_limit';
        $data['title'] = '你当前已创建'.$create_num.'个群';
        $data['result']= '0';

        if ($info['created_num'] < 1){
            $data['result']= '1';
            $data['title'] = '满足以上条件的用户可以创建1个群';
        }
        return $data;
    }

    private function checkJoinedCondition($info){
        $total_num = intval($info['joined_num'] + $info['created_num']);
        $data = array();
        $data['name']  = 'joined_limit';
        $data['title'] = '你当前已加入'.$total_num.'个群';
        $data['result']= '1';
        
        if ($total_num >= $info['max_group_num']){
            $data['result']= '0';
        }
        return $data;
    }
    
    private function checkLevelCondition($info){
        $data = array();
        $data['name']  = 'level_limit';
        $data['title'] = '普通用户等级需达到15级';
        $data['result']= '1';
        if ($info['level'] < AC::CHAT_GROUP_LEVEL_LIMIT){
            $data['result']= '0';
        }
        return $data;
    }
    
    private function checkAbilityCondition($info){
        $data = array();
        $data['name']  = 'ability_limit';
        $data['title'] = '粉粉达人可直接创建';
        $data['result']= '1';
        if (empty($info['is_ability'])){
            $data['result']= '0';
        }
        return $data;
    }
    
    private function checkCertificationMemberNumCondition($member_num){
        $data = array();
        $data['name']  = 'member_limit';
        $data['title'] = '群成员人数需要超过20人';
        $data['result']= '1';
        if ($member_num < AC::CHAT_GROUP_AUTH_MEMBERS){
            $data['result']= '0';
        }
        return $data;
    }
    
    private function checkCertificationLevelCondition($level){
        $data = array();
        $data['name']  = 'level_limit';
        $data['title'] = '群组等级需达到LV2';
        $data['result']= '1';
        if ($level < AC::CHAT_GROUP_AUTH_LEVEL){
            $data['result']= '0';
        }
        return $data;
    }

    private function checkVipCondition($info){
        $data = array();
        $data['name']  = 'vip_limit';
        $data['title'] = 'VIP用户可以额外创建3个群';
        $data['result']= '0';
        $create_max = 3;
        $levelC = $this->checkLevelCondition($info);
        $abilityC = $this->checkAbilityCondition($info);
        ( $levelC['result']==1 || $abilityC['result']==1 ) && $create_max = 4;
        if ($info['type']==2 && $info['created_num']<$create_max){
            $data['result']= '1';
            $data['title'] = 'VIP用户可以额外创建3个群';
        }
        return $data;
    }

    /**
     * VIP创建群组验证
     *
     * @param $info
     * @return array
     */
    private function checkVipConditionNew($info){
        $data = array();
        $data['status']= '0';
        $create_num = 0;
        $create_max = AC::VIP_EXTRA_CREATE_GROUP_MAX_NUM;
        $levelC = $this->checkLevelCondition($info);
        $abilityC = $this->checkAbilityCondition($info);
        ( $levelC['result'] == 1 || $abilityC['result'] == 1 ) && $create_max += AC::USER_CREATE_GROUP_MAX_NUM;
        if ($info['type']==2 && $info['created_num'] < $create_max){
            $data['status']= '1';
            $create_num = $create_max - $info['created_num'];
            $data['vip_content'] = '您是尊贵的会员，可额外创建3个群组';
            $data['ability_content'] = '达人用户，等级满15级用户可创建1个群';
        }
        $data['create_content'] = [
            'usedNum'   => strval($info['created_num']),
            'usableNum' => strval($create_num)
        ];
        return $data;
    }

    /**
     * 非会员用户创建群组验证
     *
     * @param $info
     * @return array
     */
    private function checkUserCondition($info) {
        $data = array();
        $levelC = $this->checkLevelCondition($info);
        $abilityC = $this->checkAbilityCondition($info);
        $create_num = '0';
        $data['status'] = '0';
        //用户等级大于15级或为达人用户，可建一个群
        if(($levelC['result'] == 1 || $abilityC['result'] == 1) && $info['created_num'] < AC::USER_CREATE_GROUP_MAX_NUM){
            $data['status'] = '1';
            $create_num = '1';
        }
        $data['create_content'] = [
            'usedNum'   => strval($info['created_num']),
            'usableNum' => $create_num
        ];
        return $data;
    }

    private function checkCertificationAbilityNumsCondition($gid){
        $users = $this->diaryListCacheModel->getChatGroupUsersList($gid, 0, -1);
        if ($users){
            $ability_nums = 0;
            foreach ($users as $value){
                $tmp = $this->autoUidModel->getUserInfo($value);
                if ($tmp['is_ability'] == 1){
                    $ability_nums++;
                }
            }
        }
        
        $data = array();
        $data['name']  = 'ability_num_limit';
        $data['title'] = '群内的达人数需要超过3个哦';
        $data['result']= '1';
        if ($ability_nums <= AC::CHAT_GROUP_AUTH_ABILITIES){
            $data['result']= '0';
        }
        return $data;
    }
    
    private function checkCertificationCreaterIsAbilityCondition($uid){
        $userInfo = $this->autoUidModel->getUserInfo($uid);
        
        $data = array();
        $data['name']  = 'creater_is_ability_limit';
        $data['title'] = '群主需要是达人哦';
        $data['result']= '0';
        if ($userInfo['is_ability'] == 1){
            $data['result']= '1';
        }
        return $data;
    }
    
    /**
     * 创建群
     * @param unknown $param
     * @return boolean|unknown
     */
    public function createChatGroup($param){
        // 必要参数判断
        $uid          = intval($param['uid']);
        $name         = UK::getstr($param['name'], 60,'', 1);
        $introduction = UK::getstr($param['introduction'], 1000,'...', 1);
        if (strlen($name) < 2 || $uid < 1 || strlen($introduction) < 15){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 非本人
        if($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 对创群的用户条件判断
        $access = $this->checkCreateAccess(AC::HOST_UID);
        if (!$access){
            AC::$errorNo = 'LGC003';
            return FALSE;
        }

        // 创群最大群数-人数,vip-10-100,普通-5-50
        $type              = 1;
        $max_group_members = ExpLevel::$grouplevelAddLimit[1];
        $created_num       = 0;
        $condition         = $this->checkConditions($uid);
        isset($condition['type'])                &&    $type                =    intval($condition['type']);
        isset($condition['max_group_members'])   &&    $max_group_members   =    intval($condition['max_group_members']);
        isset($condition['created_num'])         &&    $created_num         =    intval($condition['created_num']);

        // 创群数不能超过限制
        $created_num_max = 0;
        $created_num_max = $condition['level']>=AC::CHAT_GROUP_LEVEL_LIMIT ? 1 : 0;
        if (!$created_num_max){
            $created_num_max = $condition['is_ability'] ? 1 : 0;
        }
        $condition['type']==2 && $created_num_max += 3;
        if ($created_num >= $created_num_max){
            AC::$errorNo = 'LGC004';
            return FALSE;
        }
        //新的条件判断将建群数与加群数分开，此处不再验证
//        if ($created_num + $joined_num >= $max_group_num){
//            AC::$errorNo = 'LGC013';
//            return  FALSE;
//        }
        
        // 参数赋默认值
        $cover           =    '';
        $category        =    1;
        $introduction    =    '';
        
        // 群封面图片上传
        if (isset($param['cover'])){
            $cover = $this->checkCover($uid, AC::$hostUserBaseInfo['account'], $param['cover']);
        }
        isset($param['category'])        &&    $category        =    intval($param['category']);
        isset($param['introduction'])    &&    $introduction    =    UK::getstr($param['introduction'], 1000, '...', 1);
        
        // 传入参数过滤
        $data = array(
                'uid'             =>    AC::HOST_UID,
                'name'            =>    $name,
                'category'        =>    $category,
                'introduction'    =>    $introduction,
                'cover'           =>    $cover,
                'max_member_num'  =>    $max_group_members,
                'type'            =>    $type,
                'level'           =>    $type==2 ? 3 : 1,
                'time'            =>    AC::SERVER_TIME
        );

        // 创建入库
        $gid = $this->likeModel->createChatGroup($data);

        // 创建成功,加入到相应表中,备注默认为uid
        $userInfo = AC::$hostUserBaseInfo;
        $linkid = $this->likeModel->joinChatGroup($userInfo['nickname'], AC::HOST_UID, $gid);
        
        // 加入关系表
        $this->likeModel->addGroupChatLink($gid, $linkid, AC::HOST_UID, 1, AC::CHAT_GROUP_PASS_STATUS);

        // sync workman
        $chatGroupServie = new ChatGroupService();
        $chatGroupServie->syncToWorkMan($uid, 'createGroup', $gid);

        // 返回群详情
        $result = $this->likeModel->getChatGroupInfoByGid($gid);

        return $result;
    }
    
    /**
     * 编辑群信息(包括解散群)
     * @param unknown $param
     * @return boolean
     */
    public function editChatGroupInfo($param){
        // 必要参数判断
        $uid  = intval($param['uid']);
        $gid  = intval($param['gid']);
        if ($gid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        $name = '';
        if (isset($param['name'])){
            $name = UK::getstr($param['name'], 60,'', 1);
            if (strlen($name) < 1){
                AC::$errorNo = 'LGC001';
                return FALSE;
            } 
        }
        
        // 群是否存在
        $groupInfo = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($groupInfo)){
            AC::$errorNo = 'LGC005';
            return FALSE;
        }
        
        // 无权限修改
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, 0);
        if (empty($linkInfo) || $linkInfo['status'] != 1 || $linkInfo['role'] < 1){
            AC::$errorNo = 'LGC006';
            return FALSE;
        }
        
        $data = array();
        // 参数赋默认值
        isset($param['name'])           &&    $data['name']           =    $name;
        // 群封面图片上传
        if (isset($param['cover'])){
            $data['cover'] = $this->checkCover($uid, AC::$hostUserBaseInfo['account'], $param['cover']);
        }
        isset($param['category'])       &&    $data['category']       =    intval($param['category']);
        isset($param['introduction'])   &&    $data['introduction']   =    UK::getstr($param['introduction'], 1000, '', 1);
        $data['updatetime']    =    AC::SERVER_TIME;
        
        // 创建入库
        $result = $this->likeModel->editChatGroupInfo($data, $gid);
        return $result;
    }
    
    /**
     * 升级群组
     * @param unknown $param
     * @return boolean|Ambigous <boolean, Ambigous>
     */
    public function upgradeMyChatGroup($param){
        // 必要参数判断
        $uid  = intval($param['uid']);
        $gid  = intval($param['gid']);
        $attribute = intval($param['attribute']);
        if ($gid < 1 || $uid < 1 || $attribute < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 升级状态(101为申请家族群审核，201为申请学院群审核)
        $attrArr = array(101, 201);
        if (!in_array($attribute, $attrArr)){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 状态修改
        if ($attribute == 101){
            $attribute = 1;
        }else{
            $attribute = 2;
        }
        
        $certification = $this->applyForGroupCertification($param);
        $number = 1;
        foreach ($certification['condition'] as $val){
            $number *= $val['result'];
        }
        
        $result = FALSE;
        if ($number == 1){
            $data = array('attribute' => $attribute);
            $result = $this->likeModel->editChatGroupInfo($data, $gid);
        }
        
        return $result;
    }
    
    /**
     * 判断截取群封面
     * @param unknown $uid
     * @param unknown $account
     * @param unknown $coverJson
     * @return string
     */
    private function checkCover($uid, $account, $coverJson){
        $cover = '';
        // 群封面图片上传
        if ($coverJson){
            $tmp   = array();
            $cover = $coverJson;
            if (!is_array($cover)){
                return '';
            }
            $cover = array_slice($cover, 0, 8);
            foreach ($cover as $value){
                $check = UK::check_upyun_node($uid, $account, $value);
                if ($value && $check){
                    $tmp[] = $value;
                }
            }
            $cover = strval(json_encode($tmp));
        }
        return $cover;
    }
    
    /**
     * 全部群
     * @param unknown $param
     * @return boolean|multitype:|number
     */
    public function allChatGroups($param){
        $uid = intval($param['uid']);
        if ($uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        $id     =   0;
        $start  =   0;
        $gtype  =   0;
        $length =   AC::CHAT_GROUP_DISPLAY_LEN;
        isset($param['id'])       &&    $id       =    intval($param['id']);
        isset($param['gtype'])    &&    $gtype    =    intval($param['gtype']);
        isset($param['start'])    &&    $start    =    intval($param['start']);
        isset($param['length'])   &&    $length   =    intval($param['length']);
        if ($start  <   0)  $start  =   0;
        
        // 暂时默认全部为推荐群
        $recomment = 0;
        isset($param['recommend'])    &&    $recomment    =    intval($param['recommend']);

        if ($id>0 && $gtype==3){
            return [
                'counts' => 0,
                'groups' => []
            ];
        }
        
        $result = $this->likeModel->allChatGroups($start, $length, $recomment, $gtype, $id);
        if(empty($result)){
            return (Object) array();
        }
        
        $data = $tmp = array();
        foreach($result as $value){
            $tmp   =   $this->likeModel->structureChatGroupData($value, AC::HOST_UID);
            $data['groups'][] = $tmp;
        }
        $data['counts'] = count($data['groups']);
        return $data;
    }

    /**
     * 搜索群
     * @param unknown $param
     * @return boolean|Ambigous <multitype:string, multitype:string >|multitype:|number
     */
    public function searchChatGroups($param){
        $key_word  = strval(trim($param['key_word']));

        $pattern = "/^[0-9]*$/";
        preg_match($pattern, $key_word, $matches);
        
        // 搜索单个群
        if ($matches && empty($param['id'])){
            $group = $this->likeModel->getChatGroupInfoByGid(intval($key_word));
            if ($group) {
                $result['groups'][]   = $group;
                $result['counts'] = count($result['groups']);
                return $result;
            }
        }
        
        $id     =   0;
        $start  =   0;
        $length =   AC::CHAT_GROUP_DISPLAY_LEN;
        isset($param['id'])       &&    $id       =    intval($param['id']);
        isset($param['start'])    &&    $start    =    intval($param['start']);
        isset($param['length'])   &&    $length   =    intval($param['length']);
        if ($start  <   0)  $start  =   0;
        
        $result = $this->likeModel->searchChatGroupsByName($key_word, $start, $length, $id);
        if(empty($result)){
            return (Object) array();
        }
    
        $data = $tmp = array();
        foreach($result as $value){
            if (intval($value['gid']) > 0){
                $tmp   =   $this->likeModel->structureChatGroupData($value, AC::HOST_UID);
            }
            $data['groups'][] = $tmp;
        }
        $data['counts'] = count($data['groups']);
        return $data;
    }
    
    /**
     * 查看群信息
     * @param unknown $param
     * @return boolean|multitype:string
     */
    public function getChatGroupInfo($param){
        $uid = intval($param['uid']);
        $gid = intval($param['gid']);
        if (empty($gid) || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }

        $chatGroupService = new ChatGroupService();
        $group = $chatGroupService->getChatGroupInfo($gid, $uid);
        if (empty($group)) return (Object) array();

        $group['userlist'] = $chatGroupService->getChatGroupUsers($gid, $uid);

        return $group;
    
        $result = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($result)){
            AC::$errorNo = 'LGC005';
            return FALSE;
        }
        
        // 群中的用户列表
        $result['userlist'] = $tmp = array();
        $uidsArr = $this->diaryListCacheModel->getChatGroupUsersList($gid, 0, 8);
        if ($uidsArr){
            foreach ($uidsArr as $value){
                $tmp = $this->autoUidModel->getUserInfo($value);
                $tmp = $this->autoUidModel->checkIsMe($tmp);
                $tmp['nickname']    =    $this->autoUidModel->getRemarkName($tmp);
                $result['userlist']['users'][] = $tmp;
            }
            $result['userlist']['counts'] = count($result['userlist']['users']);
        }
        
        return $result;
    }
    
    /**
     * 加入群聊
     * @param unknown $param
     * @status 'apply'为申请加入
     * @return boolean|unknown
     */
    public function joinChatGroup($param){
        $uid         = intval($param['uid']);
        $gid         = intval($param['gid']);
        $author_uid  = intval($param['author_uid']);
        $content     = '';
        isset($param['content'])    &&    $content    =    UK::getstr($param['content'], 500, '', 1);
        
        if ($gid < 1 || $author_uid < 1 || $uid < 1){
             AC::$errorNo = 'LGC001';
             return FALSE;   
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 判断加入条件
        $access = $this->checkJoinAccess(AC::HOST_UID, $gid, $group);
        if (!empty(AC::$errorNo)){
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        $status = AC::CHAT_GROUP_APPLY_STATUS;
        // 官方群直接加入
        if (in_array($gid, AC::$officialGids)){
            $status = AC::CHAT_GROUP_PASS_STATUS;
        }
        
        if ($access && is_array($access) && ($access['status'] != 1)){
            if (in_array($gid, AC::$officialGids) && $access['status'] == AC::CHAT_GROUP_FIRE_STATUS){
                return FALSE;
            }
            
            if ( intval(AC::SERVER_TIME - $access['time'] < 1)){
                AC::$errorNo = 'LGC017';
                return  FALSE;
            }
            
            $data = array(
                    'status'    =>    $status,
                    'time'      =>    AC::SERVER_TIME,
                    'content'   =>    $content
            );
            
            $result = $this->likeModel->setChatGroupLinkInfo(AC::HOST_UID, $gid, $data);
            if (in_array($gid, AC::$officialGids)){
                $isMemeber = $this->checkUserIsMember($uid, $gid);
                if ($isMemeber){
                    return FALSE;
                }
                
                $this->diaryListCacheModel->addUserToChatGroup($uid, $gid);
                $this->likeModel->setChatGroupMemebers(array('member_num' => 1), $gid);
            }
            return $result;
        }
        
        $linkid = 0;
        // 查询用户信息
        $userInfo = $this->autoUidModel->getUserInfo($uid);
        if (in_array($gid, AC::$officialGids)){
            $isMemeber = $this->checkUserIsMember($uid, $gid);
            if ($isMemeber){
                return FALSE;
            }
            // 先加入用户表
            $linkid = $this->likeModel->joinChatGroup($userInfo['nickname'], $uid, $gid);
            if (!$linkid){
                AC::$errorNo = 'LGM002';
                return FALSE;
            }
            $this->likeModel->setChatGroupMemebers(array('member_num' => 1), $gid);
        }
        
        // 加入关系表
        $result = $this->likeModel->addGroupChatLink($gid, $linkid, $author_uid, $status, 0, $content);
        
        // 通知信息
        $explanation = $userInfo['nickname'].'申请加入你管理的['.$group['name'].']群';
        if (strlen($content) > 0){
            $explanation .= ',申请理由:'.$content;
        }
        
        // 给官方群组发通知
        if (in_array($gid, AC::$officialGids)){
            $explanation = $userInfo['nickname'].'加入了你管理的['.$group['name'].']群';
        }

        // 发通知
        $joinNoticeData = array(
                'uid'    =>   5,
                'mUid'   =>   $author_uid,
                'content'=>   $explanation,
                'msgType'=>   'event',
                'image'  =>   '',
                'action' =>   'pinksns://groupchat/detail/users?gid='.$gid.'&manage=1&role=1',
                'eventType'    =>    'group:application',
                'eventTypeGid' =>    $gid
        );
        $this->sendNotice($joinNoticeData);
        
        $uids = $admins = array();
        $admins = $this->likeModel->getChatGroupAdmins($gid);
        if (count($admins) > 0){
            foreach ($admins as $val){
                $joinNoticeData['mUid']   = $val['uid'];
                $joinNoticeData['action'] = 'pinksns://groupchat/detail/users?gid='.$gid.'&manage=1&role=2';
                $this->sendNotice($joinNoticeData);
            }
        }

        // sync workman
        $chatGroupServie = new ChatGroupService();
        $chatGroupServie->syncToWorkMan($uid, 'joinGroup', $gid);
        
        return $result;
    }
    
    /**
     * 邀请粉丝加入群
     * @param unknown $param
     * @return boolean
     */
    public function inviteFansToChatGroup($param){
        $uid   = intval($param['uid']);
        $gid   = intval($param['gid']);
        $tuid  = intval($param['tuid']);
        if ($gid < 1 || $tuid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 非本人登录
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 邀请人不是群成员不能邀请
        $isMemeber = 0;
        $isMemeber = $this->checkUserIsMember($uid, $gid);
        if (empty($isMemeber)){
            AC::$errorNo = 'LGC011';
            return  FALSE;
        }
        
        // 被邀请人是群成员不能被邀请
        $isMemeber = 0;
        $isMemeber = $this->checkUserIsMember($tuid, $gid);
        if ($isMemeber){
            AC::$errorNo = 'LGC012';
            return  FALSE;
        }
        
        // 被邀请人不是粉丝不能被邀请
        $isFans = $this->autoUidModel->checkUserFans($uid, $tuid);
        if (empty($isFans)){
            AC::$errorNo = 'LGC015';
            return  FALSE;
        }
        
        // 发通知
        $inviteNoticeData = array(
                'uid'    =>   $uid,
                'mUid'   =>   $tuid,
                'content'=>   '我邀请你加入['.$group['name'].']群组，快来一起happy~',
                'msgType'=>   'event',
                'image'  =>   '',
                'action' =>   'pinksns://groupchat/detail?gid='.$gid,
                'eventType'    =>    'group:application',
                'eventTypeGid' =>    $gid
        );
        $this->sendNotice($inviteNoticeData);
        return TRUE;
    }
    
    public function setChatGroupAdmins($param){
        $uid   = intval($param['uid']);
        $gid   = intval($param['gid']);
        $tuid  = intval($param['tuid']);
        if ($gid < 1 || $tuid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        $role = 0;
        isset($param['role'])    &&    $role    =    intval($param['role']);
        if (!in_array($role, array(0, 2))){
            $role = 0;
        }
        
        // 非本人登录
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 不能对本人操作
        if ($uid == $tuid){
            AC::$errorNo = 'LGC018';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 非创建者不能操作
        if ($group['uid'] != $uid){
            AC::$errorNo = 'LGC006';
            return  FALSE;
        }
        
        // 查看群管理员数,最多两个;官方群最多六个
        if ($role == 2){
            $admins = $this->likeModel->getChatGroupAdmins($gid);
            if(in_array($group['gid'], AC::$officialGids)){
	            if (count($admins) >=6){
	                AC::$errorNo = 'LGC021';
	                return  FALSE;
	            }
            }else{
            	if (count($admins) >=2){
            		AC::$errorNo = 'LGC021';
            		return  FALSE;
            	}
            }
        }
        
        // 不能操作非群成员用户
        $isMemeber = 0;
        $isMemeber = $this->checkUserIsMember($tuid, $gid);
        if (empty($isMemeber)){
            AC::$errorNo = 'LGC011';
            return  FALSE;
        }
        
        $data = array(
                'time'    =>    AC::SERVER_TIME,
                'role'    =>    $role   
        );
        
        $result = $this->likeModel->setChatGroupLinkInfo($tuid, $gid, $data);
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($tuid, $gid);
        if ($linkInfo){
            $this->likeModel->setGroupUserData($tuid, $linkInfo['linkid'], $data, $gid);
        }
        if ($result && $role == 2){
            $adminNoticeData = array(
                    'uid'    =>   5,
                    'mUid'   =>   $tuid,
                    'content'=>   '你已成为['.$group['name'].']群的管理员啦！',
                    'msgType'=>   'event',
                    'image'  =>   '',
                    'action' =>   'pinksns://groupchat/detail?gid='.$gid,
                    'eventType'    =>    'group:admin',
                    'eventTypeGid' =>    $gid
            );
            $this->sendNotice($adminNoticeData);
        }
        return $result;
    }
    
    /**
     * 退出群聊
     * @param unknown $param
     * @return boolean|Ambigous <boolean, unknown, number, resource>
     */
    public function quitChatGroup($param){
        $uid     = intval($param['uid']);
        $gid     = intval($param['gid']);
        
        if ($gid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 群主不能退出群
        if ($group['uid'] == $uid){
            AC::$errorNo = 'LGC007';
            return  FALSE;
        }
        
        // 不是群成员不能查看
        $isMemeber = $this->checkUserIsMember($uid, $gid);
        if (empty($isMemeber)){
            AC::$errorNo = 'LGC011';
            return  FALSE;
        }
        
        // 修改关系表状态
        $data = array(
                'status'    =>    AC::CHAT_GROUP_QUIT_STATUS,
                'time'      =>    AC::SERVER_TIME
        );
        $result = $this->likeModel->setChatGroupLinkInfo(AC::HOST_UID, $gid, $data);
        if ($result) {
            $this->likeModel->setChatGroupMemebers(array('member_num' => -1), $gid);
        }

        // sync workman
        $chatGroupServie = new ChatGroupService();
        $chatGroupServie->syncToWorkMan($uid, 'leaveGroup', $gid);

        return $result;
    }
    
    /**
     * 解散群
     * @param unknown $param
     * @return boolean|Ambigous <boolean, Ambigous>
     */
    public function disbandGroup($param){
        $uid     = intval($param['uid']);
        $gid     = intval($param['gid']);
        
        if ($gid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 不是群主不能解散
        if ($group['uid'] != $uid){
            AC::$errorNo = 'LGC006';
            return  FALSE;
        }
        
        $data = array();
        // 改群状态
        $data['status']         =    1;
        $data['updatetime']     =    AC::SERVER_TIME;

        $result = $this->likeModel->editChatGroupInfo($data, $gid);

        // sync workman
        $chatGroupServie = new ChatGroupService();
        $chatGroupServie->syncToWorkMan($uid, 'dismissGroup', $gid);

        // 群解散发通知
        $chatusers = $this->diaryListCacheModel->getChatGroupUsersList($gid, 0, -1);
        foreach ($chatusers as $value){
            $disbandNoticeData = array(
                    'uid'    =>   5,
                    'mUid'   =>   $value,
                    'content'=>   '你加入的['.$group['name'].']群被解散',
                    'msgType'=>   'event',
                    'image'  =>   '',
                    'action' =>   '',
                    'eventType'    =>    'group:disband',
                    'eventTypeGid' =>    $gid
            );
            $this->sendNotice($disbandNoticeData);
        }
        
        // 循环8张表，修改状态
        $this->likeModel->setGroupAllUserStatus($gid);
        return $result;
    }
    
    /**
     * 群成员列表
     * @param unknown $param
     * @return boolean|multitype:|multitype:number
     */
    public function getChatUsers($param){
        $uid = intval($param['uid']);
        $gid = intval($param['gid']);
        if ($gid < 1 || $uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::CHAT_USERS_DISPLAY_LEN;
        isset($param['start'])    &&    $start    =    intval($param['start']);
        isset($param['length'])   &&    $length   =    intval($param['length']);
        if ($start  <   0)  $start  =   0;
        
        $links = $this->likeModel->getLinkInfoByGid($gid, $start, $length);
        if (empty($links)){
            return (Object) array();
        }
        
        $data = $result = array();
        foreach($links as $value){
            $tmp = $this->likeModel->getChatUserInfoById($value['uid'], $value, $group);
            if (empty($tmp)){
                continue;
            }
            $result['users'][] = $tmp;
        }
        $result['counts'] = count($result['users']);
        return $result;
    }
    
    /**
     * 查看群聊中单个用户详情
     * @param unknown $param
     * @return boolean|multitype:string
     */
    public function getChatUserInfo($param){
        $uid   =   intval($param['uid']);
        $gid   =   intval($param['gid']);
        if (empty($uid) || empty($gid)){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 判断群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, AC::CHAT_GROUP_PASS_STATUS);
        if (empty($linkInfo)){
            AC::$errorNo = 'LGC011';
            return FALSE;
        }
        
        $result = $this->likeModel->getChatUserInfoById($uid, $linkInfo, $group);
        return $result;
    }
    
    /**
     * 我加入的群
     * @param unknown $param
     * @return boolean|multitype:|multitype:number
     */
    public function getMyJoinedGroups($param){
        // service方式调用
        $uid = intval($param['uid']);
        if ($uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }

        $userService = new UserService();
        $user    = $userService->getUserInfo($uid);
        if (empty($user)) return false;

        $chatGroupService = new ChatGroupService();
        return $chatGroupService->getUserJoinedGroups($uid);

        $uid = intval($param['uid']);
        if ($uid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        $start  =   0;
        $length =   AC::LIKE_LIST_DISPLAY_LEN;
        isset($param['start'])    &&    $start    =    intval($param['start']);
        isset($param['length'])   &&    $length   =    intval($param['length']);
        if ($start  <   0)  $start  =   0;
        
        $role   = 0;
        $status = AC::CHAT_GROUP_PASS_STATUS;
        $links  = $this->likeModel->getGroupsByUid(AC::HOST_UID, $role, $status, $start, $length);
        if (empty($links)){
            return (Object) array();
        }
        
        $data = $result = array();
        foreach($links as $value){
            $tmp = $this->likeModel->getChatGroupInfoByGid($value['gid'], 0);
            if (empty($tmp)){
                continue;
            }
            $result['groups'][] = $tmp;
        }
        $result['counts'] = count($result['groups']);
        return $result;
    }
    
    /**
     * 修改备注名
     * @param unknown $param
     * @return boolean
     */
    private function setGroupUserRemark($param){
        $uid     = intval($param['uid']);
        $gid     = intval($param['gid']);
        $remark  = UK::getstr($param['remark'], 60,'', 1);
        if ($uid < 1 || $gid < 1 ){
            AC::$errorNo = 'LGC001';
            return  FALSE;
        }
        
        // 非本人登录
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 是否有该用户
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, AC::CHAT_GROUP_PASS_STATUS);
        if (empty($linkInfo)){
            AC::$errorNo = 'LGC011';
            return FALSE;
        }
        
        // 不是本人
        if ($linkInfo['uid'] != $uid){
            AC::$errorNo = 'LGC010';
            return FALSE;
        }
        
        // 修改
        $data = array('remark' => $remark);
        $result = $this->likeModel->setGroupUserData($uid, $linkInfo['linkid'], $data, $gid);
        return $result;
    }
    
    /**
     * 群主处理请求
     * @param unknown $param
     * uid 群主 gid 群 tuid 待处理用户 status 处理结果
     * @return unknown
     */
    private function handleRequest($param){
        $uid     = intval($param['uid']);
        $gid     = intval($param['gid']);
        $tuid    = intval($param['tuid']);
        $status  = intval($param['status']);
        if ($uid < 1 || $gid < 1 || $tuid < 1 || $status < 1){
            AC::$errorNo = 'LGC001';
            return  FALSE;
        }
        // 非本人登录
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        // 不能对自己操作
        if ($uid == $tuid){
            AC::$errorNo = 'LGC019';
            return  FALSE;
        }
        
        // 操作状态
        if (!in_array($status, array(AC::CHAT_GROUP_PASS_STATUS, AC::CHAT_GROUP_IGNORE_STATUS, AC::CHAT_GROUP_FIRE_STATUS))){
            AC::$errorNo = 'LGC014';
            return  FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 无权限修改
        $linkInfo1 = $this->likeModel->getGroupUserLinkInfo($uid, $gid, 0);
        if (empty($linkInfo1) || $linkInfo1['status'] != 1 || $linkInfo1['role'] < 1){
            AC::$errorNo = 'LGC006';
            return FALSE;
        }

        $linkInfo = array();
        // 用户是否有这个请求
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($tuid, $gid, 0);
        if (empty($linkInfo)){
            AC::$errorNo = 'LGC011';
            return FALSE;
        }
        
        // 不能对管理员操作
        if ($linkInfo1['role'] == 2 &&  $linkInfo['role'] > 0){
            AC::$errorNo = 'LGC006';
            return FALSE;
        }
        
        // 用户已退出或已被踢出群
        if ($linkInfo['status'] == AC::CHAT_GROUP_QUIT_STATUS || $linkInfo['status'] == AC::CHAT_GROUP_FIRE_STATUS){
            AC::$errorNo = 'LGC016';
            return FALSE;
        }

        // 几种管理情况
        $agree = $ignore = $kick = FALSE;
        if ($linkInfo['status'] == AC::CHAT_GROUP_APPLY_STATUS && $status == AC::CHAT_GROUP_PASS_STATUS){
            // 群人数是否已满及用户已加入的群是否过载
            $access = $this->checkJoinAccess($tuid, $gid, $group, TRUE);
            if (AC::$errorNo){
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            if ($access){
                $agree = TRUE;
            }
        }
        if ($linkInfo['status'] == AC::CHAT_GROUP_APPLY_STATUS && $status == AC::CHAT_GROUP_IGNORE_STATUS){
            // 忽略加入
            $ignore = TRUE;
        }
        if ($linkInfo['status'] == AC::CHAT_GROUP_PASS_STATUS && $status == AC::CHAT_GROUP_FIRE_STATUS){
            // 踢人
            $kick = TRUE;
        }

        $linkid = 0;
        $num = array(
                AC::CHAT_GROUP_PASS_STATUS    =>    1,
                AC::CHAT_GROUP_IGNORE_STATUS  =>    0,
                AC::CHAT_GROUP_FIRE_STATUS    =>    -1
        );
        
        // 修改状态
        if ($agree || $ignore || $kick){
            // 修改状态
            $data = array(
                    'status'    =>    $status,
                    'time'      =>    AC::SERVER_TIME
            );
            $result = $this->likeModel->setChatGroupLinkInfo($tuid, $gid, $data);
        }
        
        // 同意加入
        if ($agree){
            // 先加入用户表
            $userInfo = $this->autoUidModel->getUserInfo($tuid);
            $linkid = $this->likeModel->joinChatGroup($userInfo['nickname'], $tuid, $gid);
            if (!$linkid){
                AC::$errorNo = 'LGM002';
                return FALSE;
            }
        }
        
        // 忽略请求
        if ($agree || $ignore || $kick){
            // 修改群人数
            if ($num[$status] != 0){
                $this->likeModel->setChatGroupMemebers(array('member_num' => $num[$status]), $gid);
            }
            // 修改关系表
            $data = array(
                    'status'    =>    $status,
                    'time'      =>    AC::SERVER_TIME,
                    'linkid'    =>    $linkid,
                    'role'      =>    0
            );
            
            // 官方群不去除用户
            if (in_array($gid, AC::$officialGids)){
                unset($data['linkid']);
            }
            $result = $this->likeModel->setChatGroupLinkInfo($tuid, $gid, $data);
            
            // 通过群发通知
            if ($agree){
                $agreeNoticeData = array(
                       'uid'    =>   5,
                       'mUid'   =>   $tuid,
                       'content'=>   '你的['.$group['name'].']入群申请已通过，可以开始参与互动啦！',  
                       'msgType'=>   'event',
                       'image'  =>   '',
                       'action' =>   'pinksns://groupchat/detail?gid='.$gid,
                       'eventType'    =>    'group:joined',
                       'eventTypeGid' =>    $gid
                );
                $this->sendNotice($agreeNoticeData);
            }
            
            // 被踢要发通知
            if ($kick){
                // sync workman
                $chatGroupServie = new ChatGroupService();
                $chatGroupServie->syncToWorkMan($uid, 'knockUserFromGroup', $gid, $tuid);

                $akickNoticeData = array(
                       'uid'    =>   5,
                       'mUid'   =>   $tuid,
                       'content'=>   '你被移出['.$group['name'].']群',  
                       'msgType'=>   'event',
                       'image'  =>   '',
                       'action' =>   '',
                       'eventType'    =>    'group:fired',
                       'eventTypeGid' =>    $gid
                );
                $this->sendNotice($akickNoticeData);
            }
        }
        
        return TRUE;
    }
    
    /**
     * 群未处理的事
     * @param unknown $param
     * @return multitype:|number
     */
    public function getPendingRequests($param){
        $uid = intval($param['uid']);
        $gid = intval($param['gid']);
        if ($uid < 1 || $gid < 1){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        if ($uid != AC::HOST_UID){
            AC::$errorNo = 'LGC002';
            return FALSE;
        }
        
        $groupInfo = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($groupInfo)){
            AC::$errorNo = 'LGC005';
            return FALSE;
        }
        
        // 无权限查看
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, 0);
        if (empty($linkInfo) || $linkInfo['status'] != 1 || $linkInfo['role'] < 1){
            AC::$errorNo = 'LGC006';
            return FALSE;
        }
        
        $id     =   0;
        $start  =   0;
        $length =   AC::CHAT_USERS_DISPLAY_LEN;
        isset($param['id'])       &&    $id       =    intval($param['id']);
        isset($param['start'])    &&    $start    =    intval($param['start']);
        isset($param['length'])   &&    $length   =    intval($param['length']);
        if ($start  <   0)  $start  =   0;
        
        $requests = $this->likeModel->getPendingRequests($groupInfo['uid'], $gid, $start ,$length, $id);
        if (empty($requests)){
            return (Object) array();
        }
        
        $data = array();
        foreach($requests as $value){
            $data[] = $this->likeModel->structurePendingRequestsData($value);
            $result['users'] = $data;
        }
        $result['counts'] = count($result['users']);
        return $result;
    }
    
    public function postGroupChat($param){
        $uid     = intval($param['uid']);
        $gid     = intval($param['gid']);
        $device  = UK::getstr($param['device'], 500);
        $content = UK::getstr($param['content'], 500);
        $tpl     = isset($param['tpl']) ? $param['tpl'] : 0;
        $attachments = $voices = array();
        isset($param['attachment'])    &&    $attachments    =    $param['attachment'];
        isset($param['voice'])         &&    $voices         =    $param['voice'];
        
        if ($uid < 1 || $gid < 1 || strlen($content) < 1 || empty($device)){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }

        // 非本人登录
        if (AC::HOST_UID != $uid)
        {
            AC::$errorNo    =   'LGC002';
            return  FALSE;
        }
        
        $id = 0;
        isset($param['id'])     &&  $id     =   $param['id'];
        
        // 是否禁言
        $status  =  $this->autoUidModel->checkUserStatus(AC::$hostUserBaseInfo);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 查询在群中信息
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, AC::CHAT_GROUP_PASS_STATUS);
        if (empty($linkInfo)){
            AC::$errorNo = 'LGC011';
            return FALSE;
        }
        
        $chatUserInfo = $this->likeModel->getChatUserInfoById($uid, $linkInfo, $group);
        
        // 写入数据库数据
        $info = array(
                'uid'        =>    $uid,
                'gid'        =>    $gid,
                'nickname'   =>    $chatUserInfo['remark'],
                'content'    =>    $content,
                'device'     =>    $device,
                'time'       =>    AC::SERVER_TIME
        );
        
        // 处理分享数据
        if (!empty($param['data_action']) && !empty($param['data_title']) && !empty($param['data_content']) ){

            $topicShareData = $this->topicModel->structureTopicShareData($param);
            if (!empty(AC::$errorNo)) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            $info['msgType'] = $topicShareData['msgType'];
            $info['msgData'] = $topicShareData['msgData'];
        }
        
        $id =   $this->likeModel->postGroupChat($info);
        
        // 附件判断
        $is_attachment = FALSE;
        $is_voice      = FALSE;
        if (is_array($attachments)  &&  count($attachments) > 0){
            $is_attachment = TRUE;
        }
        if (is_array($voices)  &&  count($voices) >  0){
            $is_voice = TRUE;
        }
        
        if ($is_attachment || $is_voice){
            $key           =    'GCM/'.$gid;
            $message_id    =    UK::getBodyidByItemid($key, $id);
        }
        
        // 默认为图片附件
        if ($is_attachment){
            $attachments = array_slice($attachments, 0, 1);
            $tmpInfo    =   array(
                    'uid'               =>  $gid,
                    'bodyId'            =>  1,
                    'attachment'        =>  $attachments,
                    'attachment_type'   =>  1,
                    'type'              =>  4,
                    'type_id'           =>  $message_id,
            );
            $this->diaryAttachmentModel->addDiaryAttachment($tmpInfo);
        }
        // 语音附件
        if ($is_voice){
            $voices = array_slice($voices, 0, 1);
            $voiceInfo    =   array(
                    'uid'               =>  $gid,
                    'bodyId'            =>  1,
                    'attachment'        =>  $voices,
                    'attachment_type'   =>  2,
                    'type'              =>  4,
                    'type_id'           =>  $message_id,
            );
            $this->diaryAttachmentModel->addDiaryAttachment($voiceInfo);
        }
        
        // 返回聊天列表
        if ($id)
        {
            // 返回该条记录
            $chatMessageInfo              =    $info;
            $chatMessageInfo['id']        =    $id;
            $userInfo                     =    $this->autoUidModel->getUserInfo($uid);
            $chatMessageInfo['avatar']    =    $userInfo['avatar'];
            $chatMessageInfo['tpl']       =    $tpl;
            $chatMessageInfo              =    $this->structureChatMessageData($chatMessageInfo);
            $result = (Object) array();
            if (!empty($chatMessageInfo)){
                $result = array(
                        'chats'    =>    array(),
                        'counts'   =>    1
                );
                $result['chats'][] = $chatMessageInfo;
                if (AC::OPEN_SYNC_SENDMSG_IM_STATUS && AC::$openSendChatMsg2IMVersion){
                    //处理低版本发消息新版本无法收到
                    $chatGroupService = new ChatGroupService();
                    $chatGroupService->sendMsg2GroupQueue($uid, $gid, $chatMessageInfo);
                }
            }
            
            // 更新最后发言时间
            $data = array('last_time' => AC::SERVER_TIME);
            $this->likeModel->setGroupUserData($uid, $linkInfo['linkid'], $data, $gid);
        }
        
        // 推送
        $data = array(
                'uid'      =>    $uid,
                'nickname' =>    AC::$hostUserBaseInfo['nickname'],
                'gid'      =>    $gid,
                'name'     =>    $group['name'],
                'remark'   =>    $chatUserInfo['remark'],
                'content'  =>    $content
        );
//        $push = new PushController();
//        $push->tagPush($data, "postChatgroup");
        return  $result;
    }
    
    /**
     * 获取聊天列表
     * @param unknown $param
     * @return unknown
     */
    public function getGroupChatList($param){
        $gid    =   intval($param['gid']);
        if ($gid < 0){
            AC::$errorNo = 'LGC001';
            return FALSE;
        }
        
        // 群是否存在
        $group = $this->likeModel->getChatGroupInfoByGid($gid);
        if (empty($group)){
            AC::$errorNo = 'LGC005';
            return  FALSE;
        }
        
        // 不是群成员不能拉去列表
        $isMemeber = $this->checkUserIsMember(AC::HOST_UID, $gid);
        if (empty($isMemeber)){
            AC::$errorNo = 'LGC011';
            return  FALSE;
        }
        
        // 参数处理
        $id           =   0;
        $start        =   0;
        $listModel    =   '';
        $length       =   AC::CHAT_MESSAGE_DISPLAY_LEN;
        isset($param['id'])         &&  $id         =   $param['id'];
        isset($param['listModel'])  &&  $listModel  =   $param['listModel'];
        isset($param['start'])      &&  $start      =   $param['start'];
        isset($param['length'])     &&  $length     =   $param['length'];
        if ($start  <   0)  $start  =   0;
        
        $chatList   =   $this->likeModel->getGroupChatList($start, $length, $gid, $id, $listModel);
        
        if (empty($chatList)){
            return (Object) array();
        }
        $chatMessageInfo = array();
        foreach ($chatList as $value ){
            if (count($value) < 2){
                $chatMessageInfo = $this->likeModel->getGroupChatMessageCache($gid, $value['id']);
            }else{
                $chatMessageInfo = $value;
            }
            
            $userInfo =  $this->autoUidModel->getUserInfo($chatMessageInfo['uid']);
            $chatMessageInfo['avatar']    =    $userInfo['avatar'];
            $chatMessageInfo = $this->structureChatMessageData($chatMessageInfo);
            $result['chats'][] = $chatMessageInfo;
        }
        $result['counts'] = count($result['chats']);
        
        return  $result;
    }
    
    /**
     * 组装聊天列表返回的数据结构
     * @param unknown $param
     * @return multitype:string
     */
    private function structureChatMessageData($param){
        $data = array(
                'id'    =>    '0',
                'uid'   =>    '0',
                'gid'   =>    '0',
                'nickname'    =>    '',
                'remark'      =>    '',
                'device'      =>    '',
                'content'     =>    '',
                'time'        =>    '0',
                'avatar'      =>    '',
                'msgType'     =>    '',
                'data'        =>    (Object) array(),
                'attachment'  =>    array(),
                'voiceList'   =>    array(),
                'user'        =>    (Object) array()
        );
        
        isset($param['id'])         &&  $data['id']       =   strval($param['id']);
        isset($param['uid'])        &&  $data['uid']      =   strval($param['uid']);
        isset($param['gid'])        &&  $data['gid']      =   strval($param['gid']);
        isset($param['nickname'])   &&  $data['nickname'] =   strval($param['nickname']);
        isset($param['device'])     &&  $data['device']   =   strval($param['device']);
        isset($param['content'])    &&  $data['content']  =   strval($param['content']);
        isset($param['time'])       &&  $data['time']     =   strval($param['time']);
        isset($param['avatar'])     &&  $data['avatar']   =   strval($param['avatar']);
        isset($param['msgType'])    &&  $data['msgType']  =   strval($param['msgType']);
        isset($data['avatar'])      &&  $data['avatar']   =   AC::getProtocolUriByOS($data['avatar']);
        
        // 匹配查找表情
        $emotionData = Emotion::matchEmotionDetail($data['content']);
        if ($emotionData && $emotionData['id'] > 0){
            $emotionInfo = $this->shopModel->getGoodsDetailByGoodsType($emotionData['id'], 1, 'Shop-Emotion');
            if ($emotionInfo){
                $data['msgType'] = $param['msgType'] = 'emotion';
                $msgData = array(
                        'eid'    =>    $emotionInfo['id'],
                        'etitle' =>    $emotionInfo['name'],
                        'eicon'  =>    AC::getProtocolUriByOS($emotionInfo['cover_s']),
                        'image'  =>    AC::getProtocolUriByOS($emotionData['image'])
                );
                isset($param['tpl']) && $msgData['tpl'] = $param['tpl'];
                $param['msgData'] = json_encode($msgData);
            }
        }
        
        // 私信返回附加媒体信息
        $data['data'] = $this->shopModel->restructMsgData($param['msgType'], $param['msgData']);
        
        // 获取附件
        $tmp['uid']                  =   $data['gid'];
        $tmp['last_attachment']      =   UK::getBodyidByItemid('GCM/'. $data['gid'], $data['id']);
        if ($tmp['last_attachment']){
            $attachment         =   $this->diaryAttachmentModel->getChatGroupAttachment($tmp);
            if ($attachment['attachment'] || $attachment['voiceList']){
                $data['attachment']    =    $attachment['attachment'];
                $data['voiceList']     =    $attachment['voiceList'];
            }
        }
        $user   		        =	$this->autoUidModel->getUserInfo($param['uid']);
        $data['user']           =	$this->autoUidModel->checkIsMe($user);
        $data['user']['nickname']    =    $this->autoUidModel->getRemarkName($data['user']);
        $data['nickname']            =    $data['user']['nickname'];
        
        // 群中备注
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($data['uid'], $data['gid']);
        if (!empty($linkInfo)){
            $link_tmp = array('linkid' => $linkInfo['id'], 'role' => $linkInfo['role']);
            $chat_group_user_info = $this->likeModel->getChatUserInfoById($data['uid'], $link_tmp, $data);
            if (!empty($chat_group_user_info)){
                $data['remark'] = strval($chat_group_user_info['remark']);
            }
        }
        
        // 附件支持,升级提示
        $tipsAttachment = $data['attachment'];
        if (!empty($data['voiceList'])){
            $tipsAttachment = $data['voiceList'];
        }
        $data['content'] = UK::tipsUpgrade($tipsAttachment, $data['content'], 'attachment');
        return $data;
    }
    
    /**
     * 创建群聊条件，等级或达人
     * @param unknown $uid
     * @return boolean
     */
    private function checkCreateAccess($uid){
        $userInfo = AC::$hostUserBaseInfo;
        $level = $ability = $vip = 1;
        if ($userInfo['level'] < AC::CHAT_GROUP_LEVEL_LIMIT){
            $level = 0;
        }
        
        if (empty($userInfo['is_ability'])){
            $ability = 0;
        }

        $vipInfo = $this->autoUidModel->getUserVipInfo($uid);
        empty($vipInfo) && $vip = 0;
        
        if (empty($level) && empty($ability)  && empty($vip)){
            return FALSE;
        }
        return TRUE;
    }
    
    /**
     * 加入群聊条件
     * @param unknown $uid
     * @param unknown $gid
     * @param string $check
     * @return boolean
     */
    private function checkJoinAccess($uid, $gid, $group, $check = FALSE){

        // 群是否人已满(官方群区别)
        if (in_array($gid, AC::$officialGids)){
            if ($group['member_num'] >= AC::$officialMemberNum[$gid]){
                AC::$errorNo = 'LGC008';
                return  FALSE;
            }
        }else{
            if ($group['member_num'] >= ExpLevel::$grouplevelAddLimit[$group['level']]){
                AC::$errorNo = 'LGC008';
                return  FALSE;
            }
        }
        
        // 已加入的群数是否已经到顶
        $joinedGroups = $this->likeModel->getGroupsByUid($uid, 0);
        $num = 0;
        if ($joinedGroups){
            foreach ($joinedGroups as $value){
                $groupInfo = $this->likeModel->getChatGroupInfoByGid($value['gid']);
                if($groupInfo && $value['role'] != 1){
                    $num++;
                }
            }
        }
        if ($num >= AC::USER_JOIN_GROUP_MAX_NUM){
            $vip_info = $this->autoUidModel->getUserVipInfo($uid);
            if (empty($vip_info) || $num>=AC::VIP_JOIN_GROUP_MAX_NUM){
                AC::$errorNo = 'LGC013';
                return  FALSE;
            }
        }
        
        // 以上为公用部分
        if ($check){
            return true;
        }
        
        // 是否已请求
        $linkInfo = $this->likeModel->getGroupUserLinkInfo($uid, $gid, 0);
        if (empty($linkInfo)){
            return true;
        }
        
        return $linkInfo;
    }
    
    public function getLikeMeList($likeInfo)/*{{{*/
    {
        if (empty($likeInfo['listMode']))/*{{{*/
        {
            $result =   $this->likeModel->getLikeMeList($likeInfo);
        }
        else
        {
            if ('up' == $likeInfo['listMode'])
            {
                $result =   $this->likeModel->getLikeMeListUp($likeInfo);
            }
            else
            {
                $result =   $this->likeModel->getLikeMeListDown($likeInfo);
            }
        }
        if (!empty(AC::$errorNo))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
        }/*}}}*/

        if (empty($result)  ||  !is_array($result)) return  NULL;
        foreach ($result    as  &$info)
        {
            $info['detail'] =   $this->getDetailInfo($info);
        }

        return  $result;
    }/*}}}*/

    public function getMeLikeList($likeInfo)/*{{{*/
    {
        if (empty($likeInfo['listMode']))/*{{{*/
        {
            $result =   $this->likeModel->getMeLikeList($likeInfo);
        }
        else
        {
            if ('up' == $likeInfo['listMode'])
            {
                $result =   $this->likeModel->getMeLikeListUp($likeInfo);
            }
            else
            {
                $result =   $this->likeModel->getMeLikeListDown($likeInfo);
            }
        }
        if (!empty(AC::$errorNo))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
        }/*}}}*/

        if (empty($result)  ||  !is_array($result)) return  NULL;
        foreach ($result    as  &$info)
        {
            $info['detail'] =   $this->diaryListModel->getDiaryInfoByBodyId($info['bodyId']);
        }

        return  $result;
    }/*}}}*/
    
    // 我喜欢的日记列表
    public function getMeLikeDiaryList($likeInfo)/*{{{*/
    {
        #   access = FALSE  don't have premission to access this!
        $access =   $this->checkAccessPremission($likeInfo['uid']);
        if (empty($access)) return  FALSE;
        
        $result =   $this->likeModel->getMeLikeDiaryList($likeInfo);
       
        if (!empty(AC::$errorNo))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
        }/*}}}*/
    
        if (empty($result)  ||  !is_array($result)) return  NULL;
        foreach ($result    as  &$info)
        {
           $diaryInfo =  $this->diaryListModel->getDiaryInfoByBodyId($info['bodyId']);
            if ($diaryInfo){
                $info  =   $this->feedModel->likesData($diaryInfo, $info);
                continue;
                
            }
            $info      =      $this->feedModel->feedLikesData($info);
        }
    
        return  $result;
    }/*}}}*/
    
    public function postLike($likeInfo)/*{{{*/
    {
        if (empty($likeInfo['uid'])  ||  empty($likeInfo['lUid']))
        {
            AC::$errorNo    =   'LC001';
            return  FALSE;
        }

        #   access = FALSE  don't have premission to access this!
        $access =   $this->checkAccessPremission($likeInfo['lUid']);
        if (empty($access)) return  FALSE;

        $userBaseInfo       =   $this->autoUidModel->getUserInfo($likeInfo['uid']);
        if (empty($userBaseInfo['nickname']))
        {
            AC::$errorNo    =   'LC002';
            return  FALSE;
        }

        $lUidBaseInfo       =   $this->autoUidModel->getUserInfo($likeInfo['lUid']);
        if (!isset($lUidBaseInfo['nickname']))
        {
            AC::$errorNo    =   'LC003';
            return  FALSE;
        }

        $likeInfo['nickname']   =   $userBaseInfo['nickname'];
        $likeInfo['lNickname']  =   $lUidBaseInfo['nickname'];

        if ($likeInfo['uid']    !=  $likeInfo['lUid'])
        {
            $diaryInfo  =   $this->diaryListModel->getDiaryInfoByBodyId($likeInfo['bodyId']);
            if (empty($diaryInfo['uid']) || $diaryInfo['inReview']==1)
            {
                AC::$errorNo=   'LC004';
                return  FALSE;
            }
            if (!empty($diaryInfo['secret']))
            {
                AC::$errorNo=   'LC005';
                return  FALSE;
            }
        }

        $result =   $this->likeModel->postLike($likeInfo);
        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        // 增加redis我喜欢的日记列表
        $this->diaryListCacheModel->addMeLikesList($likeInfo['uid'], $likeInfo['bodyId']);
        #  feed & statistics    /*{{{*/
        AC::$userStatistics[$likeInfo['uid']]['likeTimes']      =   1;
        AC::$userStatistics[$likeInfo['lUid']]['likeMeTimes']   =   1;
        if (isset(AC::$bodyidTypeClass[$likeInfo['type']]))
        {
            AC::$itemStatistics =   array(
                                        'likeTimes'         =>  1,
                                        'bodyidTypeClass'   =>  AC::$bodyidTypeClass[$likeInfo['type']],
                                        'uid'               =>  $likeInfo['lUid'],
                                        'bodyId'            =>  $likeInfo['bodyId'],
                                        'kitType'           =>  $likeInfo['type'],       # in Diary ,no kitType field!
                                    );
        }
        AC::$feedInfo   =   array(
                                'uid'               =>  $likeInfo['uid'],
                                'eUid'              =>  AC::$hostUserBaseInfo['uid'],
                                'eNickname'         =>  AC::$hostUserBaseInfo['nickname'],
                                'authorUid'         =>  $likeInfo['lUid'],
                                'authorNickname'    =>  $likeInfo['lNickname'],
                                'bodyId'            =>  $likeInfo['bodyId'],
                                'type'              =>  AC::FEED_LIKE,
                                'subType'           =>  $likeInfo['type'],
                                'content'           =>  $likeInfo['content'],
                            );/*}}}*/

        return  $result;
    }/*}}}*/

    public function removeLike($likeInfo)/*{{{*/
    {
        $uid = $likeInfo['uid'];
        $bodyId = $likeInfo['id'];
        isset($likeInfo['bodyId']) && $bodyId = $likeInfo['bodyId'];
        
        // 所传id不同,过两个版本左右全部按bodyId操作,去掉id的方式
        if (strlen($bodyId) > 6 ){ 
            $like = $this->likeModel->getLikeByBodyId($bodyId, $uid);
        }else{
            $like = $this->likeModel->getLikeById($bodyId, $uid);
        }
        
        if ($like['uid'] != $uid){
        	return TRUE;
        }
        if (empty($like)){
        	return TRUE;
        }
        
        $result =   $this->likeModel->removeLike($like);
        if (empty($result))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        $this->diaryListCacheModel->delMeLikesList($uid, $like['bodyId']);
        $this->diaryListCacheModel->decDiaryNums(array('likeTimes'=>1,'bodyId'=>$like['bodyId']));
        AC::$userStatistics[$uid]['likeTimes']  =   -1;
        return  $result;
    }/*}}}*/

    private function getDetailInfo($info)/*{{{*/
    {
        $type   =   $info['type'];
        $detail =   UK::getDataByBodyid($type, $info['bodyId'], ' * ');

        if (empty($detail)) $detail =   NULL;
        if (empty($detail['attachmentPath'])  ||  empty($detail['uid']) ||  empty($detail['bodyId']))   return  $detail;
        // 语音附件
        $attachment   =   $this->diaryAttachmentModel->getDiaryAllAttachment($detail);
        $detail['attachmentList']    =    $attachment['attachmentList'];
        $detail['voiceList']         =    $attachment['voiceList'];
        return  $detail;
    }/*}}}*/
    
    /**
     * 发通知
     * @param unknown $param
     * @return multitype:string number
     */
    private function sendNotice($param){
        $uid     = intval($param['uid']);
        $mUid    = intval($param['mUid']);
        $content = strval($param['content']);
        $msgType = 'text';
        $gid     = 0;
        isset($param['msgType'])      && $msgType = strval($param['msgType']);
        isset($param['eventTypeGid']) && $gid     = intval($param['eventTypeGid']);
        if (empty($uid) || empty($mUid) || AC::$errorNo) return FALSE;
        
        $data = array(
                'uid'         =>    $uid,
                'mUid'        =>    $mUid,
                'nickname'    =>    '',
                'mNickname'   =>    '',
                'content'     =>    $content,
                'msgType'     =>    $msgType,
                'eventTypeGid'=>    $gid,
                'msgData'     =>    array()
        );
        
        $userInfo  = $this->autoUidModel->getUserInfo($uid);
        $data['nickname'] = $userInfo['nickname'];
        
        $muserInfo = $this->autoUidModel->getUserInfo($mUid);
        $data['mNickname'] = $muserInfo['nickname'];
        
        $tmp = array(
                'eventType'=>    '',
                'image'    =>    '',
                'action'   =>    ''
        );
        isset($param['eventType']) &&     $tmp['eventType']  =     strval($param['eventType']);
        isset($param['image'])     &&     $tmp['image']      =     strval($param['image']);
        isset($param['action'])    &&     $tmp['action']     =     strval($param['action']);
        $data['msgData'] = strval(json_encode($tmp));

        // 发送私信
        //$this->messageBoxModel->sendMessage($data);
        $this->messageService->sendMessage($data['uid'], $data['mUid'], $data);
        if(AC::$errorNo){
	    	AC::$errorNo = NULL;
	    }
        return $data;  
    }

    /**
     * 判断是否是群成员
     * @param unknown $uid
     * @param unknown $gid
     * @return boolean
     */
    private function checkUserIsMember($uid, $gid){
        $result = FALSE;
        $gidUids = $this->diaryListCacheModel->getChatGroupUsersList($gid, 0, -1);
        if (empty($gidUids)){
            $gidUids = array();
            $users = $this->likeModel->getGidUsers($gid);
            if (empty($users)){
                return FALSE;
            }
            
            foreach ($users as $val){
                $gidUids[] = $val['uid'];
                $this->diaryListCacheModel->addUserToChatGroup($val['uid'], $gid);
            }
        }
        
        if (in_array($uid, $gidUids)){
            $result = TRUE;
        }
        return $result;
    }
    
    private function checkAccessPremission($uid)/*{{{*/
    {
        if ((AC::HOST_UID   ==  $uid))  return  TRUE;

        $array      =   array('uid' => AC::HOST_UID, 'fUid' => $uid, 'alarm' => TRUE);
        $isBlackMe  =   $this->followModel->isBlackMe($array);
        if (empty($isBlackMe))  return  TRUE;

        return  FALSE;
    }/*}}}*/
    
    private function checkAction($action)/*{{{*/
    {
        if (in_array($action, $this->actions) && method_exists($this, $action))  return  TRUE;
        AC::$errorNo    =   'SA004';
        return  ' Error : call do is not exists in LikeController! ';
    }/*}}}*/
}

